<template>
  <div>
  <section v-if="showSearch">
    <slot name="searchInput"></slot>
  </section>
  <Page v-if="showPage"  :total="totals" show-total show-elevator :current="page" :page-size="rows"
        @on-page-size-change="queryAllQuestionSize"
        @on-change="queryAllQuestionPage" style="text-align: right"/>
  <div class="questionList" v-for="(question , index) in questionLists" :key="question.questionID">
    <p>
      <Checkbox v-if="showCheckBox" label="" @on-change="selectQuestion($event,question)" v-model="question.status" :disabled="question.disabled"></Checkbox>
      <span style="margin-right:0px">{{index+1}}、</span>
      <span v-html="parseDescription(question)" v-if="question.modeCode == 4">{{parseDescription(question)}}</span>
      <span v-text="question.description" v-else>{{question.description}}</span>
      <Tag color="blue" v-for="(point,index) in filterAllPoints(question.typeCode)" :key="index">{{point}}</Tag>
      <Tag color="cyan">{{question.modeCode | modeCodeFilter}}</Tag>
      <Tag color="green">{{difficultyFilter(question.difficulty)}}</Tag>
      <template v-if="allowUpdateScore">
        <Poptip 
          title="修改分数" 
          placement="top-start" 
          transfer 
          @on-popper-hide="score = ''">
          <div slot="content" class="poptip-content">
            <Input v-model="score" number 
              placeholder="请输入1~100分">
              <Button slot="append" @click="marking(question, score)">确定</Button>
            </Input>
          </div>
          <Button icon="md-create" type="warning" ghost size="small">{{showScore ? question.score : difficultyToScoreFilter(question.difficulty)}}分</Button>
        </Poptip>
      </template>
      <Tag color="orange" v-else>{{showScore ? question.score : difficultyToScoreFilter(question.difficulty)}}分</Tag>
      <span v-if="showAnswerRight">
          <Tag v-if="question.answerRight === 1" type="dot" color="success">正确</Tag>
          <Tag v-else-if="question.answerRight === 0 && !question.userAnswers" type="dot" color="error">未作答</Tag>
          <Tag v-else type="dot" color="error">错误</Tag>
      </span>
      <Button v-if="showDels" type="error" size="small" @click="removeQuestion(question,index)" style="padding:0px 3px;float:right;"><Icon type="ios-trash" /></Button>
    </p>
    <template v-if="question.modeCode != 4">
      <p v-for="answer in question.keAnswerTOS" :key="answer.answerID" style="padding-left:20px">
        <span v-if="showUserAnswer">
          <template v-if="question.modeCode == 3">
            <span style="color: #2d8cf0;">{{question.userAnswers === '1' ? '正确' : question.userAnswers === '0' ? '错误' : ''}}</span><br>
          </template>
          <template v-else>
            <span :style="(question.userAnswers || '').includes(answer.answerID) ?'color:#2d8cf0':''" v-text="answer.description">{{answer.description}}</span>
          </template>
        </span>
        <span v-else>
          <!-- 判断题，并且只有一个答案时，显示的是唯一的正确答案，否则按选择题的方式展示答案 -->
          <template v-if="question.modeCode == 3 && question.keAnswerTOS.length === 1">
            <a>{{answer.isRight ? '正确' : '错误'}}</a>
          </template>
          <template v-else>
            <span v-if="!answer.isRight" v-text="answer.description">{{answer.description}}</span>
            <a v-if="answer.isRight" v-text="answer.description">{{answer.description}}</a>
          </template>
        </span>
      </p>
    </template>
    <p v-if="showUserAnswer && question.modeCode !== 3" style="color:darkred;margin:10px 0 0 20px;">正确答案:<span v-text="getRightAnswer(question.keAnswerTOS)">{{getRightAnswer(question.keAnswerTOS)}}</span></p>
    <p v-if="showUserAnswer && question.modeCode === 3" style="color:darkred;margin:10px 0 0 20px;">正确答案:<span v-text="getRightAnswerByJudge(question.keAnswerTOS)">{{getRightAnswerByJudge(question.keAnswerTOS)}}</span></p>
    <p v-if="showParse" style="margin:10px 0 0 20px;">解析：<span v-if="question.explanation" v-text="question.explanation">{{question.explanation}}</span><span v-else>暂无解析</span></p>
    <Divider dashed />
  </div>
  </div>
</template>

<script>
  import usally from '@/mixin/usally'
import { defined } from 'highcharts'
import { escape2Html } from '@/libs/utils'
	export default {
		name: "questionList",
    props:['allQuestionList','totals','showCheckBox','showPage','showDels','showParse','showUserAnswer','showSearch', 'showAnswerRight', 
      'allowUpdateScore', 'showScore'],
    mixins:[usally],
    data() {
      return {
          page:1,
          rows:10,
          score: ''
      }
    },
    computed:{
		  questionLists:function(){
		    this.allQuestionList.forEach(item=>{
		      if(item.answers){
		        item.keAnswerTOS = item.answers;
          }
        })
        return this.allQuestionList;
      }
    },
    filters: {
      modeCodeFilter(val) {
        switch(String(val)) {
          case '1': return '单选题'
          case '2': return '多选题'
          case '3': return '判断题'
          case '4': return '填空题'
          default: return ''
        }
      }
    },
    methods:{
      marking(question, score) {
        if (!Number.isInteger(score)) {
					this.$Message.warning('请输入整数')
					return
				}
				if (score <= 0 || score > 100) {
					this.$Message.warning('请输入1~100分')
					return
				}
        this.$set(question, 'score', score)
        document.body.click() // 控制评分组件消失
      },
      //难度对应分数过滤
      difficultyToScoreFilter(val){
        let score='';
        if(val){
          val = val.toLowerCase();
        }
        switch(val){
          case 'simple':score = 1;break;
          case 'commonly':score = 2;break;
          case 'medium':score = 3;break;
          case 'hard':score = 4;break;
        }
        return score;
      },
      setRows(rows) {
        this.rows = rows
      },
      setPage(page) {
        this.page = page
      },
      queryAllQuestionSize(size){
        this.$emit('queryListSize',size)
      },
      queryAllQuestionPage(page){
        this.page = page
        this.$emit('queryListPage',page)
      },
      changePage(page) {
        this.page = page
      },
      selectQuestion($event,question){
        let status = $event;
        let item = question
        this.$emit('selectQuestion',{status,item})
      },
      removeQuestion(question,index){
        let ques = question
        this.$emit('removeQuestion',{ques,index})
      },
      parseDescription(question){
      	if(!question.answers && !question.keAnswerTOS){
      		return;
      	}
      	let description;
      	description = question.description.replace(/\{\{.*?\}\}/g,`<span class='quesBlank' disabled style='width:40px;padding:0px 5px;outline:none;box-shadow:none;border:none;border-bottom:1px solid rgb(168,166,200);color:#2d8cf0'></span>`);
      	let el = document.createElement("div");
      	el.innerHTML = description;
      	let answersEle = el.getElementsByClassName('quesBlank');
      	let answers = question.answers || question.keAnswerTOS;
      	Array.from(answersEle).forEach((ele,index) => {
          let content = question.userAnswers || (answers[index] && answers[index].explanation) || ''
          answersEle[index].innerText = this.escape2Html(content,true);
      	});
      	return el.innerHTML;
      },
      escape2Html(str,needReplace) {
        let repStr = str.replace(/\{\{.*?\}\}/g,"___");
        let arrEntities={'lt':'<','gt':'>','nbsp':' ','amp':'&','quot':'"'};
        if(needReplace){
          return escape2Html(repStr);
        }else{
          return repStr;
        }
      },
    }
	}
</script>

<style scoped>
.questionList{
  font-size:13px;
  word-break: break-all;
}
.poptip-content {
  height: 36px;
}
.questionList /deep/ .ivu-radio-wrapper{
  white-space:normal;
}
</style>
